package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go-web/model"
	"io"
	"log"
	"math/rand"
	"os"
	"time"
)

var db *gorm.DB


func initDB(user string, password string, host string, database string) *gorm.DB {
	conn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=10s",
		user,
		password,
		host,
		database,
	)

	var db *gorm.DB
	var err error
	if db, err = gorm.Open("mysql", conn); err != nil {
		log.Fatalf("Fail to connect db : %v", err)
	}

	//defer DB.Close()

	db.LogMode(true)
	//默认加s， grom转义struct名字的时候不用加上s
	//db.SingularTable(true)

	// idle 空闲的
	db.DB().SetMaxIdleConns(40)
	db.DB().SetMaxOpenConns(40)

	return db
}

func main() {

	db = initDB(
		"root",
		"admin",
		"39.100.58.10:3306",
		"test",
	)

	rand.Seed(time.Now().UnixNano())

	gin.SetMode(gin.ReleaseMode)
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	r := gin.Default()

	r.GET("/articles", func(c *gin.Context) {
		var articles []model.Article
		db.Preload("User").Find(&articles)
		//
		c.JSON(200, gin.H{
			"data": articles,
		})
	})

	r.GET("/article/:id", func(c *gin.Context) {
		id := c.Param("id")
		fmt.Println(id)
		var article model.Article
		db.Preload("User").Preload("Comments").Preload("Comments.User").Find(&article, 1)
		//
		c.JSON(200, gin.H{
			"data": article,
		})
	})

	r.GET("/posts", func(c *gin.Context) {
		var posts []model.Post
		db.Preload("User").Find(&posts)
		//
		c.JSON(200, gin.H{
			"data": posts,
		})
	})

	r.GET("/latestComments", func(c *gin.Context) {
		var comments []model.Comment
		db.Preload("User").Preload("Article").Find(&comments)
		//
		c.JSON(200, gin.H{
			"data": comments,
		})
	})

	r.GET("/userArticles", func(c *gin.Context) {
		var user model.User
		db.Preload("Articles").Find(&user, 1)
		//
		c.JSON(200, gin.H{
			"data": user,
		})
	})

	r.GET("/batch", func(c *gin.Context) {

		n := time.Now().Nanosecond()
		longitude := fmt.Sprintf("116.%d", n)
		latitude := fmt.Sprintf("39.%d", n)

		//t := time.Now().Unix() - rand.Int63n(1000000000)
		//now := time.Unix(t, 0).Format("2006-01-02 15:04:05")

		//sql := fmt.Sprintf("insert into indexs (unique_index, normal_index, union_index_a, union_index_b, union_index_c, prefix_index, fulltext_index, geo_index, func_index) value(uuid(), rand_num(), rand_num(), rand_num(), rand_num(), rand_string(100), rand_string(200), ST_GeometryFromText('POINT(%s %s)') , '%s')", longitude, latitude, now)
		//sql := fmt.Sprintf("insert into indexs_s (union_index_a, union_index_b, union_index_c, geo_index) value(rand_string(20), rand_string(20), rand_num(), ST_GeometryFromText('POINT(%s %s)') )", longitude, latitude)
		sql := fmt.Sprintf("insert into nodes (geom) value(ST_GeometryFromText('POINT(%s %s)'))", longitude, latitude)

		db.Exec(sql)

	})

	r.Run()
}

